<template>
  <div class="course-image">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="this.percentage"
      :status="this.percentage === 100 ? 'success' : undefined"
    ></el-progress>
    <el-upload
      v-else
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :http-request="uploadImage"
      :before-upload="beforeAvatarUpload">

      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
  import { uploadCourseImage } from '@/services/course'

  export default {
    name: 'CourseImage',
    props: {
      value: {
        type: String,
        required: true,
      },
      limit: {
        type: Number,
        default: 2,
      }
    },
    data() {
      return {
        isUploading: false,
        percentage: 0,
      }
    },
    methods: {
      async uploadImage(option) {
        this.isUploading = true
        const formData = new FormData()
        formData.append('file', option.file)
        const { code, data } = await uploadCourseImage(formData, event => {
          this.percentage = Math.floor(event.loaded / event.total * 100)
        })
        if (code === '000000') {
          this.$emit('input', data.name)
          this.$message.success('上传成功')
        } else {
          this.$message.error('上传失败')
        }
        this.isUploading = false
        this.percentage = 0
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < this.limit

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
    },
  }
</script>

<style lang="scss" scoped>
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
